package com.hs.srm.admin.modules.requisition.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.pricemanagement.entity.HistoricalPriceEntity;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryQuotationEntity;
import com.hs.srm.admin.modules.pricemanagement.service.HistoricalPriceService;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryQuotationService;
import com.hs.srm.admin.modules.requisition.entity.NproPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.vo.SupplyGoodsEntityVO;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.admin.modules.vendor.vo.SimpleVendorInfoVO;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysRoleEntity;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysRoleService;
import com.hs.srm.base.modules.sys.service.SysUserService;
import com.hs.srm.common.utils.DozerUtil;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import com.landray.kmss.km.review.webservice.Exception_Exception;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @author yanfei
 * @date 2019年2月14日
 * 非生产性采购申请行项目
 */
@RestController
@RequestMapping("/nproPurchRequestItem")
public class NproPurchRequestItemController extends AbstractController {

    private static final long serialVersionUID = -4123823577744890422L;

    @Value("${hssrm.file-upload-path}")
    protected String fileUploadPath;

    @Autowired
    private NproPurchRequestItemService nproPurchRequestItemService;

    @Autowired
    private NproPurchRequestHeaderService nproPurchRequestHeaderService;

    @Autowired
    private VendorService vendorService;

    @Autowired
    private HistoricalPriceService historicalPriceService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private InquiryQuotationService inquiryQuotationService;


    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询非生产性请购单
        Long userId = this.getUser().getUserId();
        params.put("purch_request_type", "npro");
        PageUtils page = this.nproPurchRequestItemService.selectDetailPage(params);
        List<NproPurchRequestItemEntity> list = (List<NproPurchRequestItemEntity>) page.getList();
        list = EntityUtils.valToTxt(list);
        page.setList(list);
        return R.ok(page);
    }

    /**
     * 货源分配
     *
     * @param
     * @return
     */
    @RequestMapping("/toEdit/{pkId}")
    public ModelAndView toEdit(@PathVariable("pkId") String pkId) {
        //通过Id查询抬头信息
        NproPurchRequestItemEntity nproPurchRequestItemEntity = this.nproPurchRequestItemService.selectById(pkId);
        //采购申请单号
        String purchRequestCode = nproPurchRequestItemEntity.getPurchRequestCode();
        List<NproPurchRequestItemEntity> itemlist = this.nproPurchRequestItemService.findByNo(purchRequestCode, null);
	    /*if(itemlist!=null&&itemlist.size()>0){
	    	for(NproPurchRequestItemEntity ite : itemlist){
	    		//subjectCategory
	    		if("K".equals(ite.getSubjectCategory())){
	    			ite.setSubjectCategory("K-成本中心");
	    		}  
	    		if("A".equals(ite.getSubjectCategory())){
	    			ite.setSubjectCategory("A-固定资产");
	    		}
	    		if("F".equals(ite.getSubjectCategory())){
	    			ite.setSubjectCategory("F-在建工程");
	    		}
			}
	    }*/
        //把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/requisition/requisition_goodsdistribution_edit");
        modelAndView.addObject("nproPurchRequestItemEntity", nproPurchRequestItemEntity);
        modelAndView.addObject("itemlist", itemlist);
        return modelAndView;
    }

    @RequestMapping(value = "/toAllot")
    public ModelAndView toAllot(@RequestParam(value = "ids") String ids, @RequestParam(value = "inqids") String inqids) {
        //采购订单行项目id
        String str[] = ids.split(",");
        //修改 2019-07-09
        String inqid[] = inqids.split(",");//目前单选
        ArrayList<String> idsarrayList = new ArrayList<String>(Arrays.asList(str));
        /**********2019-06-23  yanfei**********************/
        List<SupplyGoodsEntityVO> itemlisttem = this.nproPurchRequestItemService.findById(idsarrayList);
        /*******2019-07-09 yanfei*********************/
        //询价的id
        ArrayList<String> inqidList = new ArrayList<String>(Arrays.asList(inqid));
        //List<InquiryQuotationEntity>  inquiryqo = this.inquiryQuotationService.findbyIds(inqidList);
        /**********2019-07-26**********************/
        List<HistoricalPriceEntity> historicalPrice = this.historicalPriceService.findbyIds(inqidList);

        /**********2019-07-26**********************/
        List<SupplyGoodsEntityVO> itemlist = new ArrayList<SupplyGoodsEntityVO>();

		/*itemlist.forEach(inquiry ->{

		});*/
        for (HistoricalPriceEntity historical : historicalPrice) {
            for (SupplyGoodsEntityVO SuVo : itemlisttem) {
                SuVo.setVendorCode(historical.getVendorCode());
                SuVo.setVendorName(historical.getVendorName());
                SuVo.setTaxCode(historical.getTaxCode());
                SuVo.setCurrency(historical.getCurrency());
                SuVo.setPriceUnit(historical.getPriceUnit());
                SuVo.setTaxPrice(historical.getPrice());
                SuVo.setPayCondition(historical.getPayCondition());
                SuVo.setCreatedBy(this.getUser().getUsername());
                itemlist.add(SuVo);
            }
        }
        /*******2019-07-09 yanfei*********************/
        //自动补全功能
        List<SimpleVendorInfoVO> vendorInfoEntitylist = this.vendorService.findSimpleAll();
        ModelAndView modelAndView = new ModelAndView("modules/requisition/requisition_goodsdistribution_edit");
        modelAndView.addObject("itemlist", itemlist);
        String jsonStr = JSON.toJSONString(vendorInfoEntitylist);
        modelAndView.addObject("vendorInfoEntitylist", jsonStr);
        return modelAndView;
    }

    /**
     * 批量提交
     */
    @SysLog("批量提交")
    @RequestMapping("/insertBatch")
    //@RequiresPermissions("inquiryHeader:insertBatch")
    public R insertBatch(@RequestBody String param) {
        // 创建一个JSONObject对象，返回数据ResponseBody用
        JSONObject jsonObject = JSONObject.parseObject(param);
        //json字符数据转成
        List<String> list = JSONArray.parseArray(jsonObject.getString("pkid"), String.class);
        //根据询价单id查询对应行项目
        List<NproPurchRequestItemEntity> nproPurchRequestItemlist = nproPurchRequestItemService.selectBatchIds(list);
        for (NproPurchRequestItemEntity nproPurchRequestItem : nproPurchRequestItemlist) {
            if (nproPurchRequestItem.getGoodsStatus() == -2) {
                nproPurchRequestItem.setGoodsStatus(-1);
                nproPurchRequestItemService.updateById(nproPurchRequestItem);
            } else {
                return R.ok().put("result", "err");
            }

        }
        return R.ok().put("result", "ok");
    }

    /**
     * 订单驳回后可修改为草稿状态
     */
    @RequestMapping("/changeStatus")
    public R changeStatus(@RequestParam(value = "pkIds[]") String[] pkIds) {
        List<NproPurchRequestItemEntity> nproPurchRequestItemlist = nproPurchRequestItemService.selectBatchIds(Arrays.asList(pkIds));
        nproPurchRequestItemlist.forEach(item -> item.setGoodsStatus(NproPurchRequestItemEntity.CAOGAO));
        boolean b = nproPurchRequestItemService.updateBatchById(nproPurchRequestItemlist);
        if (!b) {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 下载OA上传的附件
     */
    @RequestMapping("/downloadAttachment")
    public R downloadAttachment(@RequestParam(value = "attachment") String attachment, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = this.fileUploadPath + "/nproPurch_att/";
        String[] fileNames = attachment.split(";");
        File[] files = new File[fileNames.length];
        for (int i = 0; i < fileNames.length; i++) {
            files[i] = new File(filePath + fileNames[i]);
        }
        //文件下载，多文件打包zip下载,单文件直接下载
        if (files.length > 1) {
            FileUtils.zipDownload(files, "附件下载", request, response);
        } else {
            FileUtils.fileDownload(files[0], request, response);
        }
        return R.ok();
    }

    @RequestMapping("/findById")
    public R findbypkId(@RequestParam(value = "pkId[]") String[] pkId) {
        String str = pkId[0];
        NproPurchRequestItemEntity NproPurchRequestItemEntity = this.nproPurchRequestItemService.findbypkId(str);
        return R.ok(NproPurchRequestItemEntity);
    }

    /**
     * 修改所有
     */
    @SysLog("非生产性请购单修改")
    @RequestMapping("/updateAll")
    public R updateAll(String data, String pkId) {
        NproPurchRequestItemEntity NproPurchRequestItemEntity = JSONObject.parseObject(data, NproPurchRequestItemEntity.class);
        NproPurchRequestItemEntity.setPkId(pkId);
        NproPurchRequestItemEntity.setGoodsStatus(-2);
        this.nproPurchRequestItemService.updateAll(NproPurchRequestItemEntity);
        return R.msg("更新成功!");
    }

    /**
     * 删除非生产性请购单
     *
     * @param requestCode 请购单编码
     * @param pkIds       请购单头 id
     * @param reason      退单原因
     * @return
     */
    @SysLog("删除非生产性请购单")
    @RequestMapping("/deleteRequisition")
    public R deleteRequisition(@RequestParam(value = "pkId[]") String[] pkIds, String requestCode, String reason) throws Exception_Exception {

        String msg = nproPurchRequestItemService.deleteRequisition(pkIds, requestCode, reason);
        return R.msg(msg);
    }

    /**
     * @Description 获取采购组抬头信息
     * @Param [purchGroup] 采购组
     * @Return com.hs.srm.common.utils.R 返回数据
     * @Author socik
     * @Date 2019/11/7 9:27
     */
    @RequestMapping("/getCount")
    public R getCount() {
        String username = this.getUser().getUsername();
        int[] nums = new int[4];
        //所有申请单
        nums[0] = this.nproPurchRequestItemService.selectCount(new EntityWrapper<NproPurchRequestItemEntity>().eq("purch_group", username).eq("delete_flag", 0));
        //查未完成
        nums[1] = this.nproPurchRequestItemService.selectCount(new EntityWrapper<NproPurchRequestItemEntity>().eq("purch_group", username).eq("goods_status", NproPurchRequestItemEntity.CAOGAO).eq("delete_flag", 0));
        //查询询价
        nums[2] = this.nproPurchRequestItemService.selectCount(new EntityWrapper<NproPurchRequestItemEntity>().eq("purch_group", username).notIn("goods_status", -2, 0).eq("delete_flag", 0));
        //查询完成
        nums[3] = this.nproPurchRequestItemService.selectCount(new EntityWrapper<NproPurchRequestItemEntity>().eq("purch_group", username).eq("goods_status", 0).eq("delete_flag", 0));
        return R.ok(nums);
    }

    /**
     * 货源指定了状态下的货源分配
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/toSpecifyAllot")
    public ModelAndView toSpecifyAllot(@RequestParam(value = "ids") String ids, @RequestParam(value = "requestCode") String requestCode) {
        //采购订单行项目id
        String str[] = ids.split(",");
        //采购订单行项目id
        String requestCodes[] = requestCode.split(",");
        //修改 2019-07-09
        ArrayList<String> idsarrayList = new ArrayList<String>(Arrays.asList(str));
        /**********2019-06-23  yanfei**********************/
        List<SupplyGoodsEntityVO> itemlisttem = this.nproPurchRequestItemService.findById(idsarrayList);
        /*******2019-07-09 yanfei*********************/
        //比价审核通过的信息
        List<String> inqidList = new ArrayList<>();
        List<InquiryQuotationEntity> inquiryQuotationEntities = this.inquiryQuotationService.selectList(new EntityWrapper<InquiryQuotationEntity>().eq("request_code", requestCodes[0]).eq("state_", 3));
        /**********2019-07-26**********************/
        List<SupplyGoodsEntityVO> itemlist = new ArrayList<SupplyGoodsEntityVO>();

        for (int i = 0; i < inquiryQuotationEntities.size(); i++) {
            String payCondition = this.vendorService.selectByVendorCode(inquiryQuotationEntities.get(i).getVendorCode()).getPayCondition();
            for (SupplyGoodsEntityVO SuVo : itemlisttem) {
                if (inquiryQuotationEntities.get(0).getRequestCode().equals(inquiryQuotationEntities.get(i).getRequestCode())
                        && inquiryQuotationEntities.get(i).getMaterialDesc().equals(SuVo.getMaterialDesc())) {
                    SuVo.setVendorCode(inquiryQuotationEntities.get(i).getVendorCode());
                    SuVo.setVendorName(inquiryQuotationEntities.get(i).getVendorName());
                    SuVo.setTaxCode(inquiryQuotationEntities.get(i).getTaxCode());
                    SuVo.setCurrency(inquiryQuotationEntities.get(i).getCurrency());
                    SuVo.setPriceUnit(inquiryQuotationEntities.get(i).getPriceUnit());
                    SuVo.setPayCondition(payCondition);
                    SuVo.setTaxPrice(new BigDecimal(inquiryQuotationEntities.get(i).getLastEnquiryPrice()));
                    SuVo.setCreatedBy(this.getUser().getUsername());
                    itemlist.add(SuVo);
                }
            }
        }

        /*******2019-07-09 yanfei*********************/
        //自动补全功能
        List<SimpleVendorInfoVO> vendorInfoEntitylist = this.vendorService.findSimpleAll();
        ModelAndView modelAndView = new ModelAndView("modules/requisition/requisition_goodsdistribution_edit");
        modelAndView.addObject("itemlist", itemlist);
        String jsonStr = JSON.toJSONString(vendorInfoEntitylist);
        modelAndView.addObject("vendorInfoEntitylist", jsonStr);
        return modelAndView;
    }
}
